package com.gitee.tianchaohongyu.jdcl.support;

import com.gitee.tianchaohongyu.jdcl.core.CleanException;
import com.gitee.tianchaohongyu.jdcl.core.Cleaner;
import com.gitee.tianchaohongyu.jdcl.core.CleanerAnnotation;
import com.gitee.tianchaohongyu.jdcl.util.ReflectUtils;

import javax.validation.constraints.NotNull;
import java.lang.annotation.*;

/**
 * 将null视为其他值,目前支持：数值、字符串、枚举、日期，或者指定的类拥有valueOf(String) 静态方法,或者指定的类拥有接收一个字符串的构造函数。
 */
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(value = {ElementType.FIELD, ElementType.PARAMETER, ElementType.TYPE, ElementType.METHOD})
@CleanerAnnotation(NullAs.TempCleaner.class)
public @interface NullAs {

  /** 如果空将转换为到的值 */
  String value();

  /**
   * 清洗器实现
   */
  class TempCleaner implements Cleaner<Object, NullAs> {

    @Override
    public <R> R clean(R data, @NotNull Class<R> defineType, NullAs annotation) {
      if (annotation == null) throw new CleanException("未指定注解:" + NullAs.class);
      if (data != null) return data;
      return ReflectUtils.newByString(defineType, annotation.value());
    }
  }
}
